package lapsnake.model.dnd;

import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.Transferable;
import java.awt.datatransfer.UnsupportedFlavorException;
import java.io.IOException;

import lapsnake.model.LapExpression;
import lapsnake.model.LapNode;
import lapsnake.model.LapStatement;
import lapsnake.model.NodeRegister;

public class DNDTransferable<T extends LapNode> implements Transferable {

    private DataFlavor flavor;
    private T node;

    public DNDTransferable(T node) {
    	Class<? extends LapNode> nodeType = node.getClass().asSubclass(LapNode.class);
    	flavor = new DNDFlavor<>(nodeType, NodeRegister.getReadableName(nodeType));
        this.node = node;
    }

    @Override
    public DataFlavor[] getTransferDataFlavors() {
        return new DataFlavor[]{flavor};
    }

    @Override
    public boolean isDataFlavorSupported(DataFlavor flavor) {
    	if(!(flavor instanceof DNDFlavor))
    		return false;
    	DNDFlavor<?> df = (DNDFlavor<?>)flavor;
    	if(df.nodeType.isInstance(node))
    		return true;
    	//Special support
    	if(needExprWrapperFor(df.nodeType))
    		return true;
    	return false;
    }
    
    private boolean needExprWrapperFor(Class<? extends LapNode> nodeType)
	{
		return LapExpression.class.isInstance(node) && nodeType == LapStatement.class;
	}

	public T getNode() {

        return node;

    }

    @Override
    public Object getTransferData(DataFlavor flavor) throws UnsupportedFlavorException, IOException {

        Object data = null;
        if (isDataFlavorSupported(flavor)) {
            data = node;

        } else {

            throw new UnsupportedFlavorException(flavor);

        }

        return data;

    }

}